Page({
  data: {
    merchantInfo: {},
  },

  onLoad() {
    // 获取商家信息
    const merchantInfo = wx.getStorageSync("merchantInfo") || {};
    this.setData({ merchantInfo });
  },

  // 输入店铺名称
  onInputName(e) {
    this.setData({
      "merchantInfo.name": e.detail.value,
    });
  },

  // 输入店铺简介
  onInputDescription(e) {
    this.setData({
      "merchantInfo.description": e.detail.value,
    });
  },

  // 输入联系电话
  onInputPhone(e) {
    this.setData({
      "merchantInfo.phone": e.detail.value,
    });
  },

  // 选择开始时间
  onOpenTimeChange(e) {
    this.setData({
      "merchantInfo.openTime": e.detail.value,
    });
  },

  // 选择结束时间
  onCloseTimeChange(e) {
    this.setData({
      "merchantInfo.closeTime": e.detail.value,
    });
  },

  // 选择图片
  async chooseImage() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
      });

      if (res.tempFilePaths && res.tempFilePaths[0]) {
        wx.showLoading({
          title: "上传中...",
        });

        // 上传图片到云存储
        const cloudPath = `merchant/${
          this.data.merchantInfo._id
        }/avatar/${Date.now()}.jpg`;
        const uploadRes = await wx.cloud.uploadFile({
          cloudPath,
          filePath: res.tempFilePaths[0],
        });

        if (uploadRes.fileID) {
          this.setData({
            "merchantInfo.avatar": uploadRes.fileID,
          });
        }
      }
    } catch (err) {
      console.error("选择图片失败：", err);
      wx.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 保存信息
  async handleSave() {
    const { merchantInfo } = this.data;

    // 表单验证
    if (!merchantInfo.name) {
      wx.showToast({
        title: "请输入店铺名称",
        icon: "none",
      });
      return;
    }

    if (!merchantInfo.phone) {
      wx.showToast({
        title: "请输入联系电话",
        icon: "none",
      });
      return;
    }

    if (!merchantInfo.openTime || !merchantInfo.closeTime) {
      wx.showToast({
        title: "请选择营业时间",
        icon: "none",
      });
      return;
    }

    wx.showLoading({
      title: "保存中...",
    });

    try {
      const { result } = await wx.cloud.callFunction({
        name: "updateMerchantInfo",
        data: {
          merchantId: merchantInfo._id,
          ...merchantInfo,
        },
      });

      if (result.code === 0) {
        // 更新本地存储
        wx.setStorageSync("merchantInfo", merchantInfo);

        wx.showToast({
          title: "保存成功",
          icon: "success",
        });

        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: result.msg || "保存失败",
          icon: "none",
        });
      }
    } catch (err) {
      console.error("保存失败：", err);
      wx.showToast({
        title: "保存失败，请稍后重试",
        icon: "none",
      });
    } finally {
      wx.hideLoading();
    }
  },
});
